
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import java.lang.StringBuffer;
import java.lang.String;
import org.apache.http.util.EntityUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.CloseableHttpResponse;

@WebServlet(name = "dgutServlet",urlPatterns = {"/login/dgut"})
public class dgutServlet extends HttpServlet {

  //dopost():实现退出功能
   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session=request.getSession();
        String vuale=(String)session.getAttribute("usename");

        session.setAttribute("usename",null);

        response.sendRedirect("https://cas.dgut.edu.cn/logout?callback=http://localhost:8080/login.jsp");

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session =request.getSession();
        String value=(String)session.getAttribute("usename");
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost;
        CloseableHttpResponse resp1= null;
        StringBuffer params= new StringBuffer();
        System.out.println("servlet");
        if(value==null){

            String value1=request.getParameter("token");
            System.out.println("servlet1");
            try{

                // 字符数据最好encoding以下;这样一来，某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
                params.append("token=");
                params.append(value1);
                params.append("&");
                params.append("appid=javaee");
                params.append("&");
                params.append("appsecret=b3b52e43ccfd");
                params.append("&");
                params.append("userip=abc");

            } catch(Exception e1) {

                e1.printStackTrace();

            }
            System.out.println("servlet2");
            // 创建Post请求
             httpPost= new HttpPost("https://cas.dgut.edu.cn/ssoapi/v2/checkToken"+ "?"+ params);

            // 设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json)
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf8");

            try{

                // 由客户端执行(发送)Post请求
                resp1= httpClient.execute(httpPost);

                System.out.println("响应状态为:"+ resp1.getStatusLine());

                if(resp1.getEntity()!= null) {

                    Jsonb jsonb = JsonbBuilder.create();
                    String postJsonString =EntityUtils.toString(resp1.getEntity());
                    System.out.println(postJsonString);
                    //利用jsonb把json字符串转换为对象
                    Use use = jsonb.fromJson(postJsonString, Use.class);
                    int error=use.geterror();

                    if(error==1){
                        response.sendRedirect("https://cas.dgut.edu.cn?appid=javaee&state=STATE");
                    }
                    else   {
                        String access_token=use.getaccess_token();
                        String openid=use.getopenid();
                        params.delete(0,params.length());
                        try{

                            // 字符数据最好encoding以下;这样一来，某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
                            params.append("access_token=");
                            params.append(access_token);
                            params.append("&");
                            params.append("openid=");
                            params.append(openid);

                        } catch(Exception e1) {
                            e1.printStackTrace();
                        }

                        // 创建Post请求
                        httpPost= new HttpPost("https://cas.dgut.edu.cn/oauth/getUserInfo"+ "?"+ params);

                        // 设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json)
                        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf8");

                        // 响应模型
                         resp1= null;

                        try{
                            // 由客户端执行(发送)Post请求
                            resp1= httpClient.execute(httpPost);  // CloseableHttpResponse resp1= null;用reap1来获取传回来的jason字符串
                            System.out.println("响应状态为:"+ resp1.getStatusLine());
                            if(resp1.getEntity()!= null) {

                                session.setAttribute("usename","name");
                                person person1 = jsonb.fromJson(EntityUtils.toString(resp1.getEntity()), person.class);

                                session.setAttribute("username",person1.getusername());
                                session.setAttribute("name",person1.getname());
                                session.setAttribute("group",person1.getgroup());
                                session.setAttribute("openid",person1.getopenid());
                                session.setAttribute("wx_openid",person1.getwx_openid());
                                session.setAttribute("url","/login/dgut");
                                response.sendRedirect("http://localhost:8080/individual.jsp");

                            }
                        } catch(Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch(Exception e) {
                e.printStackTrace();
            }
            finally{

                try{
                    // 释放资源
                    if(httpClient!= null)
                        httpClient.close();

                    if(response!= null)
                        resp1.close();

                } catch(IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
